<template>
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body @close="cleanUploadRef()">
        <!-- prettier-ignore -->
        <el-upload 
        ref="uploadRef" 
        :limit="1" 
        accept=".xlsx, .xls" 
        :headers="upload.headers" 
        :action="upload.url"
            :disabled="upload.isUploading" :on-exceed="handleExceed" :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess" :auto-upload="false" drag>
            <i class="upload"></i>
            <div class="el-upload__text">
                将文件拖到此处，或
                <em>点击上传</em>
            </div>
        </el-upload>
        <br>
        <div class="el-upload__tip" slot="tip">
            <!-- prettier-ignore -->
            <el-link type="primary" icon="Download" @click="importTemplate">点击下载模板</el-link>
        </div>
        <!-- prettier-ignore -->
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
        <template #footer>
            <div class="dialog-footer">
                <!-- prettier-ignore -->
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <!-- prettier-ignore -->
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>


<script lang="ts" setup>
import type { ElForm, ElTable, ElUpload, FormItemRule, UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from 'element-plus'
import { ref, getCurrentInstance, reactive, toRefs, onMounted } from "vue";
const { proxy } = getCurrentInstance() as any;

import { getToken } from "@/utils/auth";
const uploadRef = ref<InstanceType<typeof ElUpload>>();
const baseURL = import.meta.env.VITE_APP_BASE_API;
// 用户导入参数
const upload = ref<any>({
    // 是否显示弹出层（用户导入）
    open: false,
    // 弹出层标题（用户导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
    // 上传的地址
    url: baseURL + "/commendation/info/importData",
});

/** 下载模板操作,需要导出给父类 */
const importTemplate = () => {
    proxy.download(
        "/commendation/info/importTemplate",
        {},
        `证书信息录入模板_${new Date().getTime()}.xlsx`
    );
};

// 导入
/** 导入按钮操作 */
const handleImport = () => {
    console.log("证书信息导入方法执行了=====");
    upload.value.title = "证书信息导入";
    upload.value.open = true;
};


/**
* 清除上传控件选中文件
*/
const cleanUploadRef = () => {
    uploadRef.value?.clearFiles();
};

// 文件上传中处理
const handleFileUploadProgress = (event: any, file: any, fileList: any) => {
    upload.value.isUploading = true;
};

// 调用父组件的getList 刷新数据
const emit = defineEmits(["get:List"]);
// 文件上传成功处理
const handleFileSuccess = (response: any, file: any, fileList: any) => {
    upload.value.open = false;
    upload.value.isUploading = false;
    // proxy.$refs.upload.clearFiles();
    cleanUploadRef();
    proxy.$alert(response.msg, "导入结果", {
        dangerouslyUseHTMLString: true,
    });
    // 成功之后刷新的数据
    emit("get:List");
};

// 提交上传文件
const submitFileForm = () => {
    proxy.$refs.uploadRef.submit();
};

// 当文件个数超过1个,覆盖前面的数据
const handleExceed: UploadProps['onExceed'] = (files) => {
    cleanUploadRef();
    const file = files[0] as UploadRawFile
    file.uid = genFileId()
    uploadRef.value!.handleStart(file)
}


defineExpose({
    // 从父组件中修改 model 的值,让弹窗能够弹跳出来
    setUpload(res: any) {
        console.log("数据初始化前==="+JSON.stringify(upload))
        upload.value.open = res.open;
        upload.value.title = res.title;
        console.log("数据初始化后==="+JSON.stringify(upload))
    }

})

</script>